
# -*- coding: utf-8 -*- 
import wx 
import math 
# 导入gui工具生成的python文件 
from datetime import datetime 
import ConfigParser
import find_frame
import mdpin_modbus
import mdpin_db
import red_map

import uart_frame
import csh_frame



begin_md_addr=11
begin_md_reg=2001
begin_md_pin_reg=2007


conf_fp='config.ini'
conf_com_port_de='COM3'
conf_com_baudrate_de='115200'

global glob_com_port,glob_com_baudrate

class FindFrame(find_frame.MdpinFrame): 
    def __init__(self,parent):
        find_frame.MdpinFrame.__init__(self,parent) 
        global glob_com_port,glob_com_baudrate 
        conf = ConfigParser.ConfigParser()   #实例化
        conf.read(conf_fp)       # 打开conf
        try:
            glob_com_port=conf.get('com','port')
            glob_com_baudrate=int(conf.get('com','baudrate'))
        except:
            conf.add_section('com')
            conf.set('com','port',conf_com_port_de)
            conf.set('com','baudrate',conf_com_baudrate_de)
            with open(conf_fp,'w') as fw:
                conf.write(fw)
            glob_com_port=conf_com_port_de
            glob_com_baudrate=int(conf_com_baudrate_de)
        print glob_com_port
        print glob_com_baudrate        

    def set_textCtrl( self, syslog,name,addr,info,other ):# 窗口信息显示
        Db_time=str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        textboxstr="%-20.20s %-20.20s %-20.20s %-25.25s %-10.10s\n"%(syslog,name,addr,info,other)
        a1=len(syslog)/20
        a2=len(name)/20
        a3=len(addr)/20
        a4=len(info)/25
        a5=len(other)/10
        big=max(a1,a2,a3,a4,a5)
        if big<1:           
            textboxstr2=Db_time+"       "+textboxstr
            self.m_textCtrl5.AppendText(textboxstr2)
        else:
            textboxstr2=Db_time+"       "+textboxstr
            print textboxstr2.decode('utf-8', 'ignore')
            self.m_textCtrl5.AppendText(textboxstr2.decode('utf-8','ignore'))
            cell=int(math.ceil(big))
            for i in range(1,cell+1):
                textboxstr="%-20.20s %-20.20s %-20.20s %-25.25s %-10.10s\n"%(syslog[20*i:],name[20*i:],addr[20*i:],info[25*i:],other[10*i:])  
                textboxstr3="%-26s"%" "+textboxstr
                self.m_textCtrl5.AppendText(textboxstr3.decode('utf-8', 'ignore'))
                print textboxstr3.decode('utf-8', 'ignore')
        return 0

    def on_btnSend_clicked(self,event):   # 发送处理函数
        addr_r = str(self.m_textCtrl8.GetValue()).split("-") 
        addr=addr_r[0]+"-"+addr_r[1]+"-"+addr_r[2][:2]

        if addr=="":
            return 0
        csv=red_map.redcsv(addr)
        if csv['addr']>0:
            modbusretrun=mdpin_modbus.md_write(glob_com_port,glob_com_baudrate,int(csv['addr']),int(csv['reg']),1)
            csv['syslog']='find '+modbusretrun
            wlweiz=csv['addr']+" "+csv['reg']
            self.set_textCtrl(csv['syslog'],addr,wlweiz,csv['info'],'',)
            #self.m_textCtrl5.AppendText(textboxstr)
            mdpin_db.db_write('histry',csv)#写入数据库
        else:
            syslog='错误:请检查reg.cvs映射表'
            self.set_textCtrl(syslog,'','','','',)
            #self.m_textCtrl5.AppendText(textboxstr)
            print self.m_textCtrl5.GetValue()
    def on_btnSend_clear(self,event):   # 发送清空函数
        addr_r = str(self.m_textCtrl8.GetValue()).split("-") 
        addr=addr_r[0]+"-"+addr_r[1]+"-"+addr_r[2][:2]
        if addr=="":
            return 0
        csv=red_map.redcsv(addr)
        if csv['addr']>0:
            modbusretrun=mdpin_modbus.md_write(glob_com_port,glob_com_baudrate,int(csv['addr']),int(csv['reg']),0)
            if modbusretrun=='sucessful':
                self.m_textCtrl8.Clear()
            else:
                syslog='清除失败！！！\n'
                self.set_textCtrl(syslog,'','','','',)
                #self.m_textCtrl5.AppendText(textboxstr)
        else:
            syslog='错误:请检查reg.cvs映射表'
            self.set_textCtrl(syslog,'','','','',)
            #self.m_textCtrl5.AppendText(textboxstr)
    def textenter( self, event ):   
        self.on_btnSend_clicked(event)

    def on_menuItemUart( self, event ):# 打开串口设置
        app = wx.App()
        window = o_UartFrame(None)
        window.Show(True)
        app.MainLoop()
    
    def on_menuItemCsh( self, event ):# 打开初始化置
        app = wx.App()
        window = o_CshFrame(None)
        window.Show(True)
        app.MainLoop()
    def onQuit( self, event ):
        self.Close()

class o_UartFrame(uart_frame.UartFrame): 
    def __init__(self,parent):
        uart_frame.UartFrame.__init__(self,parent) 
        global glob_com_port,glob_com_baudrate
        m_comboBox2Choices = [ u"COM1", u"COM2", u"COM3", u"COM4", u"COM5", u"COM6", u"COM7", u"COM8", u"COM9" ]
        m_comboBox3Choices = [ u"2400", u"4800", u"9600", u"14400", u"19200", u"28800", u"57600", u"115200" ]
        print "串口："
        print glob_com_port
        print glob_com_baudrate
        self.m_comboBox2.SetSelection( m_comboBox2Choices.index(glob_com_port) )
        self.m_comboBox3.SetSelection( m_comboBox3Choices.index(str(glob_com_baudrate)) )
    def on_btnUart_save( self, event ): # 串口设置保存
        glob_com_port=self.m_comboBox2.GetValue()
        glob_com_baudrate=self.m_comboBox3.GetValue()
        conf = ConfigParser.ConfigParser()   #实例化
        conf.read(conf_fp)       # 打开conf
        try:
            conf.set('com','port',glob_com_port)
            conf.set('com','baudrate',glob_com_baudrate)
            with open(conf_fp,'w') as fw:
                conf.write(fw)
            self.m_textCtrluart_test.Clear()
            self.m_textCtrluart_test.AppendText(u"保存成功")
        except:
            self.m_textCtrluart_test.Clear()
            self.m_textCtrluart_test.AppendText(u"error 1")
        print glob_com_port
    def on_btnTest_Uart( self, event ):# 串口测试
        read=mdpin_modbus.md_read(glob_com_port,glob_com_baudrate,begin_md_addr,2001 )
        self.m_textCtrluart_test.Clear()
        self.m_textCtrluart_test.AppendText(read)

class o_CshFrame(csh_frame.CshFrame): 
    def __init__(self,parent):
        csh_frame.CshFrame.__init__(self,parent) 
        global glob_com_port,glob_com_baudrate
    def on_btnCsh_set( self, event ): # 初始化设置
        try:
            mdpin_modbus.md_write(glob_com_port,glob_com_baudrate,170,2001,int(self.m_textCtrlSet_addr.GetValue()) )
        except:
            self.m_textCtrlSet_addr.Clear()
            self.m_textCtrlSet_addr.AppendText("请输入正确的地址")
        read=mdpin_modbus.md_read(glob_com_port,glob_com_baudrate,int(self.m_textCtrlSet_addr.GetValue()),2001 )
        self.m_textCtrlSet_addr.Clear()
        self.m_textCtrlSet_addr.AppendText(read)
